#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>

// 定义锁

pthread_mutex_t mutex;

void* mytrd1(void* arg) {
    while(1) {
        
        // 加锁
        pthread_mutex_lock(&mutex);
        printf("hello ");
        sleep(rand() % 3);
        printf("world\n");
        pthread_mutex_unlock(&mutex);

        sleep(rand() % 3);

    }

    pthread_exit(NULL);
}

void* mytrd2(void* arg) {
    while(1) {
        
        pthread_mutex_lock(&mutex);
        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");
        pthread_mutex_unlock(&mutex);

        sleep(rand() % 3);
    }

    pthread_exit(NULL);
}

int main()
{
    
    pthread_t trd1;
    pthread_t trd2;

    srand((unsigned int)time(NULL));
    
    // 初始化锁
    pthread_mutex_init(&mutex, NULL);

    int ret = pthread_create(&trd1, NULL, &mytrd1, NULL);
    if(ret != 0) {
        printf("pthrad_create error: %s\n", strerror(ret));
        return -1;
    }

    ret = pthread_create(&trd2, NULL, &mytrd2, NULL);
    if(ret != 0) {
        printf("pthrad_create error: %s\n", strerror(ret));
        return -1;
    }
    
    pthread_join(trd1, NULL);
    pthread_join(trd2, NULL);

    pthread_mutex_destroy(&mutex);

    return 0;
}

